package com.atguigu.gmall.activity.receiver;

import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @author: JC
 * @date: 2021/11/15 14:02
 */
@Component
public class SeckillReceiver {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TASK_1,durable ="true" ,autoDelete = "false"),
            exchange = @Exchange(value =MqConst.EXCHANGE_DIRECT_TASK ,durable = "true",autoDelete = "false"),
            key = {MqConst.ROUTING_TASK_1}
    ))
    @SneakyThrows
    public void importToRedis(String msg, Message message, Channel channel){

        QueryWrapper<SeckillGoods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper
                .eq("status",1)
                .gt("stock_count",0)
                .eq("DATE_FORMAT(start_time,'%Y-%m-%d')",
                        DateUtil.formatDate(new Date()));

        // 查询当天的秒杀商品数据集合：当天，审核状态，剩余库存数
        List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectList(goodsQueryWrapper);
        if(CollectionUtils.isEmpty(seckillGoods)){
            // 没有商品
         return;
        }
        // 将集合数据放入缓存中
        seckillGoods.stream().forEach(seckillGoods1 -> {
            // 判断当前商品在缓存中是否存在，
            Boolean result = redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS).hasKey(seckillGoods1.getSkuId().toString());
            if(!result){
                // 使用hash 数据类型保存商品
                // key = seckill:goods field = skuId
                // 判断缓存中是否有当前key

                // 将数据放入缓存 数据类型
                redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS).put(seckillGoods1.getSkuId().toString(),seckillGoods1);

                // 如何控制库存超卖？ 将商品是库存数量放入缓存！ num=10; 放list数据中
                for (Integer integer = 0; integer < seckillGoods1.getStockCount(); integer++) {
                    // 商品id为field ，对象为value 放入缓存
                    // key = seckill:goods field = skuId value=商品字符串
                    String key = RedisConst.SECKILL_STOCK_PREFIX+seckillGoods1.getSkuId();
                    redisTemplate.opsForList().leftPush(key,seckillGoods1.getSkuId().toString());

                }
                // 状态为初始化为1
                redisTemplate.convertAndSend("seckillpush",seckillGoods1.getSkuId()+":1");
            }

        });

        // 手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }
}
